﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.ServiceModel.DomainServices.Client;
using C1.Silverlight.DataGrid;
using Lite.ExcelLibrary.SpreadSheet;
using System.IO;

namespace DYSales.Views.Stock
{
    public partial class pd_page : Page
    {
        public pd_page()
        {
            InitializeComponent();
            dg_pds.AutoGeneratingColumn += other.GetOther().dg_AutoGeneratingColumn;
            Loaded += new RoutedEventHandler(pd_page_Loaded);
            Unloaded += new RoutedEventHandler(pd_page_Unloaded);
            bt_新建.Click += new RoutedEventHandler(bt_新建_Click);
            bt_添加.Click += new RoutedEventHandler(bt_添加_Click);
            bt_保存.Click += new RoutedEventHandler(bt_保存_Click);
            bt_放弃修改.Click += new RoutedEventHandler(bt_放弃修改_Click);
            bt_删除.Click += new RoutedEventHandler(bt_删除_Click);
            dg_pds.SelectionChanged += dg_pds_SelectionChanged;
            bt_取拼音简码.Click += new RoutedEventHandler(bt_取拼音简码_Click);
            bt_导出.Click += new RoutedEventHandler(bt_导出_Click);
            bt_导入.Click += new RoutedEventHandler(bt_导入_Click);
            bt_退货.Click += new RoutedEventHandler(bt_退货_Click);
            bt_进货.Click += new RoutedEventHandler(bt_进货_Click);
            bt_超量.Click += new RoutedEventHandler(bt_超量_Click);
        }

        void bt_超量_Click(object sender, RoutedEventArgs e)
        {
            dm.getDS().Load(dm.getDS().GetSetPdtableQuery(), LoadBehavior.RefreshCurrent, le =>
            {
                dg_pds.DataContext = le.Entities;
            }, null);
        }

        void bt_导入_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog oFile = new OpenFileDialog();
            oFile.Filter = "所有文件(*.*)|*.*|Excel2007文件(*.xlsx)|*.xlsx|Excel2003文件(*.xls)|*.xls";
            if (oFile.ShowDialog() == true)
            {
                FileStream fs;
                try
                {
                    fs = oFile.File.OpenRead();
                }
                catch (IOException ex)
                {
                    var box = other.GetMessageBox();
                    box.Title = "东雅进销存系统提示";
                    box.tbk_text.Text = ex.Message;
                    box.Show();
                    return;
                }
                string nFileName = Guid.NewGuid().ToString() + oFile.File.Extension;
                byte[] fsData = new byte[fs.Length];
                fs.Read(fsData, 0, fsData.Length);
                dm.getDS().UploadFile(nFileName,
                    fsData, lo =>
                    {
                        dm.getDS().Importfile(nFileName, new int[] { 0 }, true, le =>
                        {
                            var list = le.Value;
                            var listRows = new List<Web.PdTable>();
                            foreach (var item in list[0].rows)
                            {
                                var rq = new Web.PdTable();
                                List<string> dt = item.data.ToList();
                                rq.p_商品编号 = dt[0];
                                rq.p_商品名称 = dt[1];
                                rq.p_单价 = other.checkDecimal(dt[2]) ? decimal.Parse(dt[2]) : 0;
                                rq.p_拼音简码 = dt[3];
                                rq.p_库存数量 = other.checkDecimal(dt[4]) ? decimal.Parse(dt[4]) : 0;
                                rq.p_条形码 = dt[5];
                                rq.p_进货价 = other.checkDecimal(dt[6]) ? decimal.Parse(dt[6]) : 0;
                                rq.p_单位 = dt[7];
                                rq.p_库存下限 = other.checkDecimal(dt[8]) ? decimal.Parse(dt[8]) : 0;
                                rq.p_商品类别 = dt[9];
                                rq.p_折扣 = other.checkDouble(dt[10]) ? double.Parse(dt[10]) : 1;
                                listRows.Add(rq);
                            }
                            if (listRows.Count > 0)
                            {
                                var listp = listRows.Select(p => p.p_商品名称).ToList();
                                dm.getDS().Load(dm.getDS().GetExtPdtableQuery(listp), lp =>
                                {
                                    if (lp.Entities.Count() == 0)
                                    {
                                        foreach (var item in listRows)
                                        {
                                            if (!item.HasValidationErrors)
                                            {
                                                dm.getDS().PdTables.Add(item);
                                            }
                                        }
                                        dg_pds.DataContext = dm.getDS().PdTables;
                                    }
                                    else
                                    {
                                        var box = other.GetMessageBox();
                                        box.Title = "东雅进销存系统提示";
                                        box.tbk_text.Text = "发现已经存在的商品，禁止导入操作。";
                                        box.Show();
                                    }
                                }, null);
                            }
                            else
                            {
                                var box = other.GetMessageBox();
                                box.Title = "东雅进销存系统提示";
                                box.tbk_text.Text = "导入文件没有可用数据";
                                box.Show();
                            }
                        }, null);
                    }, null);
            }
        }

        ciwn_addStock addWin;
        void bt_进货_Click(object sender, RoutedEventArgs e)
        {
            addWin = new ciwn_addStock();
            addWin.Show();
        }

        cwin_unStock usWin;
        void bt_退货_Click(object sender, RoutedEventArgs e)
        {
            if (dg_pds.Selection.SelectedRows.Count == 1)
            {
                var pd = dg_pds.Selection.SelectedRows.First().DataItem as Web.PdTable;
                usWin = new cwin_unStock();
                usWin.tb_商品名称.Text = pd.p_商品名称;
                usWin.max = pd.p_库存数量;
                usWin.pdid = pd.id;
                usWin.Show();
            }
        }

        void bt_导出_Click(object sender, RoutedEventArgs e)
        {
            if (dg_pds.DataContext != null)
            {
                SaveFileDialog sDialog = new SaveFileDialog();
                sDialog.DefaultExt = "*.xls";
                sDialog.DefaultFileName = "东雅进销存商品库";
                sDialog.Filter = "Excel Files(*.xls)|*.xls";
                if (sDialog.ShowDialog() == true)
                {
                    Workbook workbook = new Workbook();
                    Worksheet worksheet = new Worksheet("东雅进销存商品库");
                    int col = 0;
                    foreach (var column in dg_pds.Columns.OrderBy(column => column.DisplayIndex))
                    {
                        worksheet.Cells[0, col] = new Cell(column.GetColumnText());
                        col++;
                    }

                    col = 0;
                    int rowct = 1;
                    foreach (var row in dg_pds.Rows)
                    {
                        foreach (var column in dg_pds.Columns.OrderBy(column => column.DisplayIndex))
                        {
                            worksheet.Cells[rowct, col] = new Cell(column.GetCellText(row));
                            col++;
                        }
                        col = 0;
                        rowct++;
                    }
                    workbook.Worksheets.Add(worksheet);
                    using (Stream sFile = sDialog.OpenFile())
                    {
                        workbook.Save(sFile);
                    }
                    var box = other.GetMessageBox();
                    box.Title = "东雅进销存系统";
                    box.tbk_text.Text = "数据导出完成！";
                    box.Show();
                }
            }
        }

        void bt_取拼音简码_Click(object sender, RoutedEventArgs e)
        {
            var nv = g_dataform.DataContext as Web.PdTable;
            if (nv != null)
            {
                dm.getDS().GetPR(nv.p_商品名称, lp =>
                {
                    nv.p_拼音简码 = lp.Value;
                }, null);
            }
        }

        void dg_pds_SelectionChanged(object sender, DataGridSelectionChangedEventArgs e)
        {
            if (dg_pds.Selection.SelectedRows.Count == 1)
            {
                var pd = dg_pds.Selection.SelectedRows.First().DataItem as Web.PdTable;
                g_dataform.DataContext = pd;
            }
        }

        List<Web.PdTable> delpds;
        void bt_删除_Click(object sender, RoutedEventArgs e)
        {
            if (dg_pds.Selection.SelectedRows.Count > 0)
            {
                delpds = new List<Web.PdTable>();
                foreach (var item in dg_pds.Selection.SelectedRows.ToList())
                {
                    delpds.Add(item.DataItem as Web.PdTable);
                }
                var list = delpds.Select(p => p.p_商品名称).ToList();
                dm.getDS().CheckPdIsSelledOrInven(list, lo =>
                {
                    if (!lo.Value)
                    {
                        var box = other.GetMessageBox();
                        box.Title = "东雅进销存提示";
                        box.tbk_text.Text = "删除的商品中有销售过或正在盘点的商品。所以不能进行删除操作";
                        box.Show();
                        return;
                    }
                    else
                    {
                        var box = other.GetMessageBox();
                        box.Title = "东雅进销存系统";
                        box.tbk_text.Text = "确定要删除当前所选中的资料吗？此操作完成后系统将无法恢复被删除的资料！";
                        if (dm.getDS().HasChanges)
                        {
                            box.tbk_text.Text += "(当前的资料存在已修改过项，继续进行删除操作系统将放弃所有修改项再执行删除操作)";
                        }
                        box.Closed += box_Closed;
                        box.Show();
                    }
                }, null);
            }
        }

        void box_Closed(object sender, EventArgs e)
        {
            bt_放弃修改_Click(null, null);
            var result = sender as cwin_Question;
            result.Closed -= box_Closed;
            if (result.DialogResult.Value)
            {
                foreach (var item in delpds)
                {
                    var rq = dm.getDS().PdTables.FirstOrDefault(c => c.id.Equals(item.id));
                    if (rq != null)
                    {
                        dm.getDS().PdTables.Remove(rq);
                    }
                }
                dm.getDS().SubmitChanges(le =>
                {
                    dg_pds.DataContext = dm.getDS().PdTables;
                }, null);
            }
        }

        void bt_放弃修改_Click(object sender, RoutedEventArgs e)
        {
            other.GetOther().dg_RejectChanges(dg_pds);
        }

        void bt_保存_Click(object sender, RoutedEventArgs e)
        {
            if (dm.getDS().HasChanges)
            {
                bt_保存.IsEnabled = false;
                dm.getDS().SubmitChanges(lo =>
                {
                    bt_保存.IsEnabled = true;
                }, null);
            }
        }

        void bt_添加_Click(object sender, RoutedEventArgs e)
        {
            if (g_dataform.DataContext != null)
            {
                var nv = g_dataform.DataContext as Web.PdTable;
                if (nv.ValidationErrors != null && nv.ValidationErrors.Count > 0)
                {
                    return;
                }
                dm.getDS().checkPd(nv.p_商品编号, nv.p_商品名称, lo =>
                {
                    if (!lo.HasError && lo.Value)
                    {
                        if (nv.p_拼音简码 == null)
                        {
                            dm.getDS().GetPR(nv.p_商品名称, lp =>
                            {
                                nv.p_拼音简码 = lp.Value;
                                dm.getDS().PdTables.Add(nv);
                                createPd();
                            }, null);
                        }
                    }
                    else
                    {
                        var box = other.GetMessageBox();
                        box.Title = "东雅软件";
                        box.tbk_text.Text = "该商品编号或商品名称已存在";
                        box.Show();
                    }
                }, null);
            }
        }

        void pd_page_Unloaded(object sender, RoutedEventArgs e)
        {
            dg_pds.AutoGeneratingColumn -= other.GetOther().dg_AutoGeneratingColumn;
            bt_放弃修改_Click(null, null);
        }

        void bt_新建_Click(object sender, RoutedEventArgs e)
        {
            createPd();
            tb_编号.Focus();
        }

        void createPd()
        {
            bindccb();
            var npd = new Web.PdTable();
            npd.p_商品编号 = string.Empty;
            npd.p_商品名称 = string.Empty;
            npd.p_单价 = 0;
            npd.p_库存数量 = 0;
            npd.p_条形码 = string.Empty;
            npd.p_进货价 = 0;
            npd.p_单位 = string.Empty;
            npd.p_库存下限 = 0;
            npd.p_折扣 = 1;
            npd.p_商品类别 = string.Empty;
            g_dataform.DataContext = npd;
        }

        void pd_page_Loaded(object sender, RoutedEventArgs e)
        {
            refresh();
        }

        void refresh()
        {
            dm.getDS().Load(dm.getDS().GetPdTablesQuery(), LoadBehavior.RefreshCurrent, le =>
            {
                if (!le.HasError)
                {
                    dg_pds.DataContext = dm.getDS().PdTables;
                }
            }, null);
        }

        void bindccb()
        {
            ccb_分类.Items.Clear();
            var listsk = dm.getDS().PdTables.GroupBy(p => p.p_商品类别).Select(p => p.First()).Select(p => p.p_商品类别);
            foreach (var item in listsk)
            {
                var cbi = new C1.Silverlight.C1ComboBoxItem();
                cbi.Content = item;
                ccb_分类.Items.Add(cbi);
            }
            ccb_单位.Items.Clear();
            var listut = dm.getDS().PdTables.GroupBy(p => p.p_单位).Select(p => p.First()).Select(p=>p.p_单位);
            foreach (var item in listut)
            {
                var cbi = new C1.Silverlight.C1ComboBoxItem();
                cbi.Content = item;
                ccb_单位.Items.Add(cbi);
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

    }
}
